package status

import (
	"encoding/json"
	"fmt"
	"net/url"
	"renrenwaigua/oauth"
	"strconv"
)

func GetList(t *oauth.Transport, ownerId int64, pageSize int, pageNumber int) ([]status, error) {
	uid := strconv.FormatInt(ownerId, 10)
	tok := t.Token.AccessToken

	vals := url.Values{}
	vals.Set("access_token", tok)
	vals.Set("ownerId", uid)

	//the pagesize must be [1-100],the defallt pagesize is 20
	if pageSize > 0 {
		vals.Set("pageSize", strconv.FormatInt(int64(pageSize), 10))
	}
	//the pagenumber must be: pagenumber > 0,the default pagenumber is 1
	if pageNumber > 0 {
		vals.Set("pageNumber", strconv.FormatInt(int64(pageNumber), 10))
	}
	url := apiSatatus + apiSatstusList + "?" + vals.Encode()

	r, err := t.Client().Get(url)
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	defer r.Body.Close()

	ress := responses{}
	err = json.NewDecoder(r.Body).Decode(&ress)
	if err != nil {
		return nil, err
	}

	if r.StatusCode != 200 {
		fmt.Println("status code:", r.StatusCode)

		buf := make([]byte, 1024)
		n, err := r.Body.Read(buf)
		if err != nil {
			fmt.Println("status:getlist:body read:", err.Error())
		} else {
			fmt.Println("status:getlist:body:", string(buf[:n]))
		}
	}

	stts := make([]status, len(ress.Response))
	for k, v := range ress.Response {
		stts[k] = v
	}
	return stts, nil
}
